<?php

namespace app\api\service;

use app\common\exception\BaseException;

/**
 * 微信api基类
 * Class wechat
 * @package app\library
 */
class WxBase
{
    protected $appId;
    protected $appSecret;

    protected $error;

    /**
     * 构造函数
     * WxBase constructor.
     * @param $appId
     * @param $appSecret
     */
    public function __construct($appId = null, $appSecret = null)
    {
        $this->setConfig($appId, $appSecret);
    }

    protected function setConfig($appId = null, $appSecret = null)
    {
        !empty($appId) && $this->appId = $appId;
        !empty($appSecret) && $this->appSecret = $appSecret;
    }

    /**
     * 获取access_token
     * @return mixed
     */
    public function getAccessToken()
    {
        $cacheKey = $this->appId . '@access_token';
        if(!$access_token = cache($cacheKey)){
            // 请求API获取 access_token
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
            $result = $this->curl($url);
            $data = $this->jsonDecode($result);
            
            cache($cacheKey, $data['access_token'], $data['expires_in']);
            $access_token = $data['access_token'];
        }

        return $access_token;
    }

    
    /**
     * 获取session_key
     * @return mixed
     */
    public function sessionKey($code)
    {
        /**
         * code 换取 session_key
         * ​这是一个 HTTPS 接口，开发者服务器使用登录凭证 code 获取 session_key 和 openid。
         * 其中 session_key 是对用户数据进行加密签名的密钥。为了自身应用安全，session_key 不应该在网络上传输。
         */
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $result = json_decode($this->curl($url, [
            'appid' => $this->appId,
            'secret' => $this->appSecret,
            'grant_type' => 'authorization_code',
            'js_code' => $code
        ]), true);
        if (isset($result['errcode'])) {
            $this->error = $result['errmsg'];
            return false;
        }
        return $result;
    }
    
    
    /**
     * 发送公众号模板消息
     * 微信官方已关闭
     * 
     */
    public function sendMsg($params)
    {
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=$access_token";
        
        $data = [
            'touser' => $params['openid'], 
            'mp_template_msg' => [
                'appid' => 'wx4008e79eff4b4fe2',  //公众号appid
                'template_id' => 'ZG8ht2NYYiBd2-kLnftMt8B7bQVH99RVU57QAvo7zCI',  //消息模板ID
                'url' => 'http://weixin.qq.com/download',  //公众号模板消息所要跳转的url
                //公众号模板消息所要跳转的小程序，小程序的必须与公众号具有绑定关系
                'miniprogram' => ['appid'=>$this->appId,'path'=>'/pages/mine/order/order'],
                'data' => [
                    'first' => ['value'=>$params['desc'],'color'=>'#990000'], //first不支持颜色设置
                    'keyword1' => ['value'=>$params['order_sn'],'color'=>'#990000'],
                    'keyword2' => ['value'=>$params['service_project'],'color'=>'#173177'],
                    'keyword3' => ['value'=>1,'color'=>'#173177'],
                    'keyword4' => ['value'=>$params['time'],'color'=>'#173177'],
                    'remark' => ['value'=>'祝您生活愉快','color'=>'#173177'],
                ]
            ]
        ];
        
        $result = $this->post($url,json_encode($data));
        return $result;
    }
    

    /**
     * curl请求指定url (get)
     * @param $url
     * @param array $data
     * @return mixed
     */
    function curl($url, $data = [])
    {
        // 处理get数据
        if (!empty($data)) {
            $url = $url . '?' . http_build_query($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//https请求 不验证证书和hosts
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    /**
     * 模拟POST请求
     * @param $url
     * @param array $data
     * @param bool $useCert
     * @param array $sslCert
     * @return mixed
     */
    public function post($url, $data = [], $useCert = false, $sslCert = [])
    {
        $header = [
            'Content-type: application/json;'
        ];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_POST, TRUE);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        if ($useCert == true) {
            // 设置证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($curl, CURLOPT_SSLCERTTYPE, 'PEM');
            curl_setopt($curl, CURLOPT_SSLCERT, $sslCert['certPem']);
            curl_setopt($curl, CURLOPT_SSLKEYTYPE, 'PEM');
            curl_setopt($curl, CURLOPT_SSLKEY, $sslCert['keyPem']);
        }
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    /**
     * 数组转json
     * @param $data
     * @return string
     */
    protected function jsonEncode($data)
    {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    /**
     * json转数组
     * @param $json
     * @return mixed
     */
    protected function jsonDecode($json)
    {
        return json_decode($json, true);
    }

    /**
     * 返回错误信息
     * @return mixed
     */
    public function getError()
    {
        return $this->error;
    }


}
